<template>
    <rx-dialog @handOk="handleSubmit" @cancel="cancel">
      <a-form :form="form" style="padding-right: 12px;height: 100%;">
        <a-form-item style="display:none;">
          <a-input v-decorator="['userId']"/>
          <a-input v-decorator="['relTypeId']"/>
          <a-input v-decorator="['mainDepId']"/>
        </a-form-item>
            <div class="rxContent">
                <a-divider orientation="left">{{i18n('list.information','基本信息')}}</a-divider>
            <a-row>
                <a-col :span="12">
                    <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.name','姓名')">
                        <a-input :placeholder="i18n('form.name','姓名','input')" v-decorator="['fullName', {rules: [{required: true, message: i18n('form.name','姓名','input')}]}]"/>
                    </a-form-item>
                    <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.accountNum','账号')">
                        <a-input :placeholder="i18n('form.accountNum','账号','input')" v-decorator="['userNo', {rules: [{required: true, message: i18n('form.accountNum','账号','input')}]}]"/>
                    </a-form-item>
                    <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.weComAccount','企业微信账号')">
                        <a-input :placeholder="i18n('form.weComAccount','企业微信账号','input')" v-decorator="['wxOpenId', {rules: [{required: false, message: i18n('form.weComAccount','企业微信账号','input')}]}]"/>
                    </a-form-item>
                </a-col>
              <a-col :span="12">
                <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.head','头像')">
                  <div class="uploadBox" style="width: 150px;height: 150px;margin-top: 4px;">
                    <a-upload
                    name="files"
                    listType="picture-card"
                    class="avatar-uploader"
                    :showUploadList="false"
                    action="/api/api-system/system/core/sysFile/upload"
                    :headers="headers"
                    :beforeUpload="beforeUpload"
                    @change="handleChange"
                    style="width: 100%;height: 100%;"
                  >
                    <img v-if="imageUrl" :src="imageUrl" alt="photo" class="userHeadPortrait" style="max-width: 100%;object-fit: cover" />
                    <div v-else>
                      <a-icon :type="loading ? 'loading' : 'plus'" />
                      <div class="ant-upload-text">{{$ti18('rxList.upload','上传')}}</div>
                    </div>
                  </a-upload>
                  </div>
                </a-form-item>
              </a-col>

            </a-row>
            <a-row>
              <a-col :span="12">
                <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.userType','用户类型')">
                  <a-select :placeholder="i18n('form.userType','用户类型','select')"
                            v-decorator="['userType', {rules: [{required: false, message: i18n('form.userType','用户类型','select')}]}]"
                            :getPopupContainer="p=>p.parentNode">
                    <a-select-option value="">{{i18n('pleaseSelect','请选择...')}}</a-select-option>
                    <a-select-option :key="userType.code" v-for="userType in osUserTypes">{{userType.name}}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.birthday','出生日期')">
                  <a-date-picker :format="birthdayFormat" :placeholder="i18n('form.birthday','出生日期','select')" v-decorator="['birthday', {rules: [{required: false, message: '请输入出生日期'}]}]"/>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row v-if="!this.mdl.userId || this.mdl.userId=='' ">
              <a-col :span="12">
                <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.password','密码')">
                  <a-input-password :placeholder="i18n('form.password','密码','input')" v-decorator="['pwd', {rules: [{required: true, message: i18n('form.password','密码','input')}]}]"/>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.reenterPwd','重输密码')">
                  <a-input-password :placeholder="i18n('form.reenterPwd','重输密码','input')"  v-decorator="['repwd', {rules: [{required: true, message: i18n('form.reenterPwd','重输密码','input')}]}]"/>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="12">
                <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.entryTime','入职时间')">
                  <a-date-picker :format="dateFormat" showTime :placeholder="i18n('form.entryTime','入职时间','select')"  v-decorator="['entryTime', {rules: [{required: false, message: i18n('form.entryTime','入职时间','select')}]}]"/>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.sex','性别')">
                  <a-radio-group buttonStyle="solid" defaultValue="male" v-decorator="['sex', {initialValue:'male',rules: [{required: false, message: i18n('form.sex','性别','select')}]}]">
                    <a-radio-button value="male">{{i18n('male','男士')}}</a-radio-button>
                    <a-radio-button value="female">{{i18n('female','女士')}}</a-radio-button>
                  </a-radio-group>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row >
                <a-col :span="12">
                    <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.index','序号')">
                        <a-input-number  :placeholder="i18n('form.index','序号','input')" :min="1" v-decorator="['sn', {rules: [{required: false, message: i18n('form.index','序号','input')}]}]"/>
                    </a-form-item>
                </a-col>
              <a-col :span="12" v-show="this.mdl.status&&this.mdl.status!='1'">
                <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.resignTime','离职时间')">
                  <a-date-picker :format="dateFormat" showTime :placeholder="i18n('form.resignTime','离职时间','select')" v-decorator="['quitTime', {rules: [{required: false, message: i18n('form.resignTime','离职时间','select')}]}]"/>
                </a-form-item>
              </a-col>
            </a-row>
            <a-divider orientation="left">{{i18n('list.departAndGroup','部门与组')}}</a-divider>
            <a-row>
              <a-col :span="12">
                <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.mainDepName','主部门')">
                  <a-input-group compact style="display: flex;margin-top: 6px;">
                    <a-input readOnly v-decorator="['mainDepName', {rules: [{required: true, message: i18n('form.mainDepName','主部门','select')}]}]" style="flex: 1;"/>
                      <a-button @click="openGroup"  style="width: 50px">·&nbsp;·&nbsp;·</a-button>
                  </a-input-group>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.otherGroup','其他组')" class="userGroup">
                    <a-button @click="openCanGroup" type="primary" style="margin-right: 10px;">{{i18n('select','选择...')}}</a-button>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row>
                <a-col :span="12" v-for="(dimGroup,index) in dimArray" :key="index"  >
                  <a-form-item :label="dimGroup.dimName" class="selectitem" :labelCol="labelCol" :wrapperCol="wrapperCol">
                    <rx-text-box-list :ref="'groupDim_'+dimGroup.dimId" :value="{value:dimGroup.groupIds,text:dimGroup.groupNames}"></rx-text-box-list>
                  </a-form-item>
                </a-col>
            </a-row>
                <a-divider orientation="left">{{i18n('list.contactWay','联系方式')}}</a-divider>
                <a-row >
                    <a-col :span="12">
                        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.phoneNum','手机')">
                            <a-input :placeholder="i18n('form.phoneNum','手机','input')" v-decorator="['mobile', {rules: [{required: false, message: i18n('form.phoneNum','手机','input')}]}]"/>
                        </a-form-item>
                    </a-col>

                    <a-col :span="12">
                        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.email','邮件')">
                            <a-input :placeholder="i18n('form.email','邮箱','input')" v-decorator="['email', {rules: [{required: false, message: i18n('form.email','邮箱','input')}]}]"/>
                        </a-form-item>
                    </a-col>

                    <a-col :span="12">
                        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.qqNumber','QQ号')">
                            <a-input :placeholder="i18n('form.qqNumber','QQ号','input')" v-decorator="['qq', {rules: [{required: false, message: i18n('form.qqNumber','QQ号','input')}]}]"/>
                        </a-form-item>
                    </a-col>

                    <a-col :span="12">
                        <a-form-item :labelCol="labelCol" :wrapperCol="{span:20}" :label="i18n('form.address','地址')">
                            <a-input :rows="4" :placeholder="i18n('form.address','地址','input')" v-decorator="['address', {rules: [{required: false, message: i18n('form.address','地址','input')}]}]" />
                        </a-form-item>
                    </a-col>

                    <a-col :span="12">
                        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.urgentContact','紧急联系人')">
                            <a-input :placeholder="i18n('form.urgentContact','紧急联系人','input')" v-decorator="['urgent', {rules: [{required: false, message: i18n('form.urgentContact','紧急联系人','input')}]}]"/>
                        </a-form-item>
                    </a-col>

                    <a-col :span="12">
                        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.urgentPhone','紧急联系人手机')">
                            <a-input :placeholder="i18n('form.urgentPhone','紧急联系人手机','input')" v-decorator="['urgentMobile', {rules: [{required: false, message: i18n('form.urgentPhone','紧急联系人手机','input')}]}]"/>
                        </a-form-item>
                    </a-col>
                </a-row>
                <ExtendedProperties :propertiesGroups="propertiesGroups"></ExtendedProperties>
            </div>

      </a-form>
  </rx-dialog>
</template>
<script>
  import OsUserApi from '@/api/user/org/osUser'
  import OsusertypeApi from '@/api/user/org/osUserType'
  import ExtendedProperties from './ExtendedProperties'
  import osPropertiesGroupApi from '@/api/user/org/osPropertiesGroup'
  import { BaseForm,RxDialog,Dialog,RxTextBoxList,Util,TokenUtil} from "@lowcode/jpaas-common-lib"
  import moment from 'moment';
  import LoginApi from '@/api/login'
  import {sm2} from 'sm-crypto'
  import dayjs from "dayjs";

  export default {
    name: 'OsUserEdit',
    props: {
      groupId:{type:String,default:""},
      relTypeId:String,
      newAndJoin:{type:Boolean,default:false},
      tenantId:{type:String,default:""},
      isGrade:{type:Boolean,default:false},
      group:{},
    },
    components: {
      RxDialog,
      RxTextBoxList,
      ExtendedProperties
    },
    mixins:[BaseForm],
    data () {
      return {
        osUserTypes:[],
        mainDepId:'',
        birthdayFormat:'YYYY-MM-DD',
        dateFormat:'YYYY-MM-DD HH:mm:ss',
        dimArray:[],//用户当前的用户组维度
        imageUrl:"",
        loading:false,
        headers:{},
        jindu:0,
        propertiesGroups:[],
        joinGroupId:"",
        groupName:'',
        //密码模式
        passwordmode: "default",
        // 国产sm2公钥
        sw2PublicKey: process.env.VUE_APP_SM2_PUBLIC_KEY,
      }
    },
    beforeCreate () {
    },
      created () {
      if(this.newAndJoin){
            this.joinGroupId=this.groupId;
      }
      if(!this.pkId){
        this.getPasswordmode();
      }

      var token =TokenUtil.getToken();
      if (token) {
        this.headers['Authorization'] = 'Bearer ' + token // 让每个请求携带token--['Authorization']为自定义key 请根据实际情况自行修改
      }
      OsusertypeApi.getAllUserTypeList({tenantId:this.tenantId}).then(data=>{
        this.osUserTypes=data;
      });

      OsUserApi.edit(this.pkId,this.groupId,this.tenantId).then(data=>{
        this.dimArray=data.dimArray;
        //console.log(this);
        this.form.setFieldsValue({mainDepId:data.mainDepId,mainDepName: data.mainDepName,relTypeId:this.relTypeId,sn:data.sn});
        this.setGroupName();
      });
      this.getPropertiesGroups();
    },
    methods: {
      i18n(name,text,key){
            return this.$ti18(name,text,"osUser",key);
      },
      get(id){
        return OsUserApi.getOsUser(id,this.tenantId);
      },
      setGroupName(){
          if(!this.pkId &&  this.groupId ) {
              if (this.group){
                  this.groupName = this.group.name;
              }

              var jsons=this.dimArray;
              for(var i=0;i<jsons.length;i++){
                  //判断当前部门的组织维度是不是行政组织，如果是则清掉行政组织输入框的部门名，并显示到主部门。
                  if (jsons[i].hasOwnProperty('groupNames') && jsons[i].dimName == '行政组织') {
                      this.form.setFieldsValue({mainDepId: jsons[i].groupIds, mainDepName: jsons[i].groupNames});
                      jsons[i].groupNames = '';
                      jsons[i].groupIds = '';
                      break;
                  }
              }

          }

      },
      validForm(values){
        if(values.pwd!=values.repwd){
          this.$message.error(this.i18n('inconsistent','两次输入的新密码不一致!'))
          return false;
        }
        return true;
      },
      //获取密码加密模式的配置参数
      getPasswordmode() {
        let self = this;
        LoginApi.getLoginConfig().then((res) => {
            let result = res.data;
            //密码加密模式
            self.passwordmode = result.passwordmode;
        });
      },
      sm2Encrypt(password) {
        const sm2 = require('sm-crypto').sm2
        let pwd= sm2.doEncrypt(password, this.sw2PublicKey);
        return pwd.toString();
      },
      save(values){
        var canGroupIds="";
        for(var groupDim in this.$refs) {
          if (groupDim == 'groupDim_1' && this.$refs[groupDim][0].valData.contains(values.mainDepId)) {
            this.$message.error(this.i18n('cannotSame','其他部门不能与主部门选择一致！'));
            return;
          }
          var val = this.$refs[groupDim][0].getValue().value;
          if (val) {
            canGroupIds += val + ",";
          }
        }
        values.canGroupIds=canGroupIds.substring(0,canGroupIds.length-1);
        if(values.birthday){
          values.birthday=values.birthday.format(this.dateFormat)
        }
        if(values.entryTime){
          values.entryTime=values.entryTime.format(this.dateFormat)
        }
        if(values.quitTime){
          values.quitTime=values.quitTime.format(this.dateFormat)
        }
        values.tenantId=this.tenantId;
        values.photo=this.photo;
        values.propertiesGroups=this.propertiesGroups;
        values.newAndJoin=this.newAndJoin;
        values.joinGroupId=this.joinGroupId;
        if(!values.userId && "sm2"==this.passwordmode){
          values.isSm2Password='YES';
          values.repwd = this.sm2Encrypt(values.repwd);
          values.pwd = this.sm2Encrypt(values.pwd);
        }
        return OsUserApi.saveOsUser(values);
      },
      onload_(values){
        if(values){
          if(values.birthday){
              if(values.birthday && typeof values.birthday==='number'){
                  values.birthday = dayjs(values.birthday).format(this.dateFormat)
              }
            values.birthday=moment(values.birthday, this.dateFormat);
          }
          if(values.entryTime){
              if(values.entryTime && typeof values.entryTime==='number'){
                  values.entryTime = dayjs(values.entryTime).format(this.dateFormat)
              }
            values.entryTime=moment(values.entryTime, this.dateFormat);
          }
          if(values.quitTime){
            if(values.quitTime && typeof values.quitTime==='number'){
              values.quitTime = dayjs(values.quitTime).format(this.dateFormat)
            }
            values.quitTime=moment(values.quitTime, this.dateFormat);
          }
          if(values.photo) {
            this.imageUrl = this.getFilePath(values.photo);
          }
        }
      },
      openGroup(){
        Dialog.openGroupDialog({curVm: this,data:{single:true,dimId:'1',showDimId:false,tenantId:this.tenantId}, widthHeight: ['1000px','600px']},function(self,data){

            var jsons=self.dimArray;
          //console.log("data" + jsons);
          for(var i=0;i<jsons.length;i++) {
            if(jsons[i].dimId=="1") {
              var groupDim = self.$refs['groupDim_' + jsons[i].dimId][0];
              var groupIds = groupDim.valData;
              for (var j = 0; j < groupIds.length; j++) {
                if (data.groupId == groupIds[j]) {
                  self.$message.warning(data.name + self.i18n('isOtherGroup','为其他组！'), 2);
                  return;
                }
              }
            }
          }
          self.form.setFieldsValue({mainDepId:data.groupId,mainDepName:data.name});
        })
      },
      getFilePath(fileId){
        let token = TokenUtil.getToken();
        fileId=Util.encryptWord(fileId);
        return "/api/api-system/system/core/sysFile/previewFile?fileId=" + fileId + "&accessToken=" + token;
      },
      handleChange(info) {
        if (info.file.status === 'uploading') {
          this.loading = true;
          return;
        }
        if (info.file.status === 'done') {
          var res=info.fileList[0].response;
          if(res.success){
            this.photo=res.data[0].fileId;
            this.imageUrl=this.getFilePath(res.data[0].fileId);
            this.loading=false;
          }
        }
      },
      beforeUpload(file) {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
          this.$message.error(this.i18n('onlyImage','只能上传图片!'));
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
          this.$message.error(this.i18n('imageLimit','图片必须小于2MB!'));
        }
        return isJpgOrPng && isLt2M;
      },
      openCanGroup(){
        Dialog.openGroupDialog({curVm: this,data:{isGrade:this.isGrade,single:false,showDimId:true,tenantId:this.tenantId}, widthHeight: ['1000px','600px']},function(self,data){

            var mainDepId=self.form.getFieldValue("mainDepId");
          for(var i=0;i<data.length;i++) {
            var groupId = data[i].groupId;
            if(mainDepId==groupId){

              self.$message.warning(data[i].name+ self.i18n('isMainDepart','为主部门！'),2);
              data.splice(i,1);
            }
          }
          var jsons=self.dimArray;
          for(var i=0;i<jsons.length;i++){
            var groupDim=self.$refs['groupDim_'+jsons[i].dimId][0];
            var groupIds=groupDim.valData;
            var groupNames=groupDim.labData;
            for(var j=0;j<data.length;j++){
              var group=data[j];
              if(jsons[i].dimId==group.dimId){
                if(!groupIds.includes(group.groupId)){
                  groupIds.push(group.groupId);
                  groupNames.push(group.name);
                  jsons[i].groupIds=groupIds.join(",");
                  jsons[i].groupNames=groupNames.join(",");
                }
              }
            }
          }
          self.dimArray = [...jsons];
        })
      },
      //获取用户扩展属性组
      getPropertiesGroups(){
        var ownerId="";
        if(this.pkId){
          ownerId=this.pkId;
        }
        osPropertiesGroupApi.getAllProperties({dimId:"-1",ownerId:ownerId,tenantId:this.tenantId}).then(res=>{
          this.propertiesGroups=res;
        });
      }
    }
  }
</script>
<style scoped>
  .userGroup >>> .rx-textBoxList-container{
    margin-top: 6px;
  }
  .userHeadPortrait{
    max-width: 100%;
    max-height: 100%;
    object-fit:contain;
  }
  .rxContent{
      padding: 10px;
  }
 .selectitem >>> .ant-form-item-control{
    margin-top: 7px;
  }

</style>